package com.wanmait.gohome.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.gohome.mapper.AutomatchMapper;
import com.wanmait.gohome.mapper.ConfigMapper;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wanmait.gohome.mapper.InformationMapper;
import com.wanmait.gohome.pojo.Automatch;
import com.wanmait.gohome.pojo.Config;
import com.wanmait.gohome.pojo.Information;
import com.wanmait.gohome.pojo.Userinfo;
import com.wanmait.gohome.service.InformationService;
import com.wanmait.gohome.util.FaceMatch;
import com.wanmait.gohome.util.SysContext;
import org.apache.ibatis.annotations.Mapper;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.io.File;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class InformationServiceImpl implements InformationService {
    @Resource
    private  InformationMapper informationMapper;
    @Resource
    private ConfigMapper configMapper;
    @Resource
    private AutomatchMapper automatchMapper;

    @Resource
    private HttpSolrClient client;

    @Resource
    private RedisTemplate<String,String> redisTemplate;


    public List<Information> findAllList(){
        return informationMapper.findAllList();
    }
  public void pageviews(Integer id){//浏览量
   /* return informationMapper.pageviews(id);*/
     informationMapper.pageviews(id);

  }
    @Override
    public void updateStateNable(Information information) {
     informationMapper.updateStateNable(information);
     informationMapper.updateNews(information);

    }
    @Override
    public Information loserdetails(Information information) {
        return informationMapper.findinformation(information);
    }




    @Override
    public void insert(Information object) {
        informationMapper.insert(object);
        redisTemplate.opsForList().rightPush("information:list",object.getId()+"");
    }

    @Override
    public void update(Integer id) {
        informationMapper.updateId(id);
    }

    @Override
    public void delete(Integer id) {

    }

    @Override
    public void delete(String ids) {

    }

    @Override
    public List<Information> findAll() {
        return null;
    }

    @Override
    public Information findById(Integer id) {
        return null;
    }

    @Override
    public PageInfo<Information> lookupTypePage(Information information) {
        int pageNum= SysContext.getPageNum();
        int pageSize=0;

        try {
            Config config = configMapper.selectManagePageInteger();
            pageSize = Integer.parseInt(config.getConfigValue());//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }


        PageHelper.startPage(pageNum,pageSize);//pageSize

        List info    = informationMapper.lookupType(information);


        PageInfo pageInfo = new PageInfo<>(info,7);

        return pageInfo;
    }

    @Override
    public PageInfo<Information> auditShow() {
        int pageNum= SysContext.getPageNum();
        int pageSize=0;

        try {
            Config config = configMapper.selectManagePageInteger();
            pageSize = Integer.parseInt(config.getConfigValue());//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }


        PageHelper.startPage(pageNum,pageSize);//pageSize

        List info    = informationMapper.auditShow();


        PageInfo pageInfo = new PageInfo<>(info,7);

        return pageInfo;
    }

    @Override
    public PageInfo<Information> findLoserShow(String name) {
        int pageNum= SysContext.getPageNum();
        int pageSize=0;

        try {
            Config config = configMapper.selectManagePageInteger();
            pageSize = Integer.parseInt(config.getConfigValue());//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }

        PageHelper.startPage(pageNum,pageSize);//pageSize

        List<Information> information    = informationMapper.findLoserShow(name);

        PageInfo<Information> pageInfo = new PageInfo<>(information, 7);

        return pageInfo;
    }


    @Override
    public PageInfo<Information> findPage() {//所有分页
        int pageNum= SysContext.getPageNum();
        int pageSize=0;

        try {
            Config config = configMapper.selectManagePageInteger();
            pageSize = Integer.parseInt(config.getConfigValue());//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }


        PageHelper.startPage(pageNum,pageSize);//pageSize

        List info    = informationMapper.findAll();


        PageInfo pageInfo = new PageInfo<>(info,7);

        return pageInfo;
    }

    @Override
    public List<Information> findAll(Information object) {
        return null;
    }

    @Override
    public PageInfo<Information> findPage(Information object) {

       return null;

    }

    @Override
    public void insertPerson(Information information){//寻亲者找人信息发布
        informationMapper.insertPerson(information);
        redisTemplate.opsForList().rightPush("information:list",information.getId()+"");
    }



    /**
     * 志愿者添加信息
     * @param information
     */
    @Override
    public void insertByVolunteer(Information information) {
        informationMapper.insertByVolunteer(information);
        redisTemplate.opsForList().rightPush("information:list",information.getId()+"");
    }


    public PageInfo<Information> selectList(Information information) {//前台所有信息显示分页
        int pageNum= SysContext.getPageNum();
        int pageSize=10;
        try {
            //pageSize = Integer.parseInt();//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }

        PageHelper.startPage(pageNum,pageSize);//pageSize

        List<Information> informations    = informationMapper.selectList(information);

        PageInfo<Information> pageInfo = new PageInfo<>(informations, 7);

        return pageInfo;
    }

    public PageInfo<Information> selectList1(Information information) {//前台所有信息显示分页
        int pageNum= SysContext.getPageNum();
        int pageSize=10;
        try {
            //pageSize = Integer.parseInt();//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }

        PageHelper.startPage(pageNum,pageSize);//pageSize

        List<Information> informations    = informationMapper.selectList1(information);

        PageInfo<Information> pageInfo = new PageInfo<>(informations, 7);

        return pageInfo;
    }

    public Information findByInformation(Integer id)
    {
        /*informationMapper.findByInformation(id);*/
        return informationMapper.findByInformation(id);
    }

    /**
     *
     * @param userId 个人中心 发布的寻亲信息
     * @return
     */
    @Override
    public PageInfo<Information> findByUserId(Integer userId) {

        int pageNum = SysContext.getPageNum();
        int pageSize = 6;
        PageHelper.startPage(pageNum,pageSize);
        List<Information> informations = informationMapper.findByUserId(userId);
        PageInfo<Information> pageInfo = new PageInfo<>(informations,5);
        return pageInfo;
    }


    /**
     *
     * @param informationId 个人中心 删除寻亲启事
     */
    @Override
    public void deleteByInformationId(Integer informationId) {
        informationMapper.deleteByInformationId(informationId);
    }



    @Override
    public PageInfo<Information> findByTitle(String titles) {//条件搜索界面默认显示第一页
        List<Information> informations = new ArrayList<>();
        int pageNum = SysContext.getPageNum();
        int pageSize = 10;
//        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Information> pageInfo=null;
        try {
            SolrQuery query = new SolrQuery();
            //设置查询条件
            query.setQuery("name:"+titles);
            //设置分页
            //从哪一条开始查询 (pageNum-1)*pagesize
            query.setStart((pageNum-1)*pageSize);
            //查询条数 pageSize
            query.setRows(pageSize);
            //设置高亮
            query.setHighlight(true);
            //设置高亮字段 可以用逗号分开指定多个高亮字段
            query.set("hl.fl", "name");
            //查询
            QueryResponse response = client.query("information",query);
            //获得高亮数据
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            Information  information = null;
            Userinfo userinfo = null;
            //获得所有的文档集合
            SolrDocumentList documentList = response.getResults();
            for (SolrDocument document : documentList) {
                information = new Information();
                String id = (String) document.getFieldValue("id");
                information.setId(Integer.parseInt(id));
                information.setName(highlighting.get(id).get("name").get(0));
                information.setEnable(true);
                String pic=(String) document.getFirstValue("pic");
                information.setPic(pic);
                String sex=(String) document.getFirstValue("sex");
                information.setSex(sex);
                String lostPlace=(String) document.getFirstValue("lostPlace");
                information.setLostPlace(lostPlace);
                String findPlace=(String) document.getFirstValue("findPlace");
                information.setFindPlace(findPlace);
                String blood=(String) document.getFirstValue("blood");
                information.setBlood(blood);
                String presentAddress=(String) document.getFirstValue("presentAddress");
                information.setPresentAddress(presentAddress);
                informations.add(information);
            }
            pageInfo= new PageInfo<Information>(informations,7);
            pageInfo.setPages(((int)documentList.getNumFound()-1)/pageSize+1);
            pageInfo.setPageNum(pageNum);
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    /**
     *
     * @param id  个人中心 首页 查找发布信息数量
     * @return
     */
    @Override
    public Integer findCountByUserId(Integer id) {

        return informationMapper.findCountByUserId(id);
    }

    /**
     *
     * @param information  个人中心 修改寻亲信息
     */
    @Override
    public void updateByInformationId(Information information) {
        informationMapper.updateByInformationId(information);
    }

    /**
     *
     * @param informationId
     * @return   通过ID 查询寻亲启事
     */
    @Override
    public Information findByInformationId(Integer informationId) {
        return informationMapper.findByInformationId(informationId);
    }


    /**
     * 自动匹配
     */
    @Override
    public void auotmatch(String path)
    {
        long length = redisTemplate.opsForList().size("information:list");
        for(int j=0;j<length;j++){
            String listValue = redisTemplate.opsForList().index("information:list",0);
            if(listValue!=null)
            {
                Integer informationId = Integer.parseInt(listValue);
                Information information = informationMapper.findByInformationId(informationId);

                String filePath1 = path + information.getPic();
                File file = new File(path);
                String[] fileName = file.list();
                List<Information> informations = informationMapper.selectByName(information.getName(), information.getSex());

                for (int i = 0; i < fileName.length; i++) {
                    String filePath2 = path + fileName[i];
                    String result = FaceMatch.match(filePath1, filePath2);

                    JsonObject jObject = new JsonParser().parse(result).getAsJsonObject();
                    JsonElement jsonElement = jObject.get("result");
                    float score = 0;
                    if (!jsonElement.isJsonNull()) {    //人脸对比出错的话，这里是空的                 节点判断是否为空
                        score = jsonElement.getAsJsonObject().get("score").getAsFloat();
                    }
                    if (score >= 80) {
                        Information information1 = informationMapper.selectByPic(information.getName(), fileName[i], information.getSex());
                        if (information1 != null) {
                            informations.add(information1);
                        }
                    }
                }
                for(int i=0;informations!=null&&i<informations.size();i++){
                    automatchMapper.insertAutomatch(informationId, informations.get(i).getId());
                }

                redisTemplate.opsForList().leftPop("information:list");
            }
        }

    }

}
